import {patch, cascade, fetch} from '../../../utils/axios'

const state = {
  name: '编辑主机',
  type: {},
  terminal_time: null,
  emenu: false,
  fields: {},
  re_per: {},
  status: {},
  valid: null,
  hostnameRules: [
    (v) => !!v || '请输入主机名'
  ],
  ipRules: [
    (v) => !!v || '请输入IP'
  ],
  uuidRules: [
    (v) => !!v || '请输入UUID'
  ],
  typeRules: [
    (v) => !!v || '请输选择类型'
  ],
  msg: {
    uuid: '',
    ip: '',
    ilo_ip: '',
    vip: ''
  }
}

const mutations = {
  editHost (state, payload) {
    if (payload.validate()) {
      var url = '/hosts/' + state.fields.id + '/'
      patch(url,
        state.fields
      ).then((response) => {
        this._vm.$data.$$state.listhost.editdialog = false
      }).catch((error) => {
        if (error.response) {
          let datas = error.response.data
          for (var name in datas) {
            state.msg[name] = datas[name]
          }
        }
      })
    }
  },
  deleteHost (state) {
    let r = confirm('确认删除？')
    if (r === true) {
      var url = '/hosts/' + state.fields.id + '/'
      cascade(url).then((response) => {
        this._vm.$data.$$state.listhost.editdialog = false
      }).catch((error) => {
        console.log(error.response.data.detail)
      })
    }
  },
  closeEditHost (state) {
    this._vm.$data.$$state.listhost.editdialog = false
    let msg = this.msg
    for (var i in msg) {
      msg[i] = ''
    }
  },
  loadEditHost (state, payload) {
    let url = '/hosts/' + payload + '/'
    fetch(url, {
    }).then((response) => {
      state.fields = response
    }).catch((error) => {
      alert(error.response)
    })
    state.type = this._vm.$data.$$state.listhost.type
    state.re_per = this._vm.$data.$$state.listhost.re_per
    state.status = this._vm.$data.$$state.listhost.status
  }
}

const actions = {
  editHost ({commit, state}, payload) {
    commit('editHost', payload)
  },
  deleteHost ({commit}) {
    commit('deleteHost')
  },
  closeEditHost ({commit}) {
    commit('closeEditHost')
  },
  loadEditHost ({commit}, payload) {
    commit('loadEditHost', payload)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
